var express = require('express');
var router = express.Router();
var { RoomModel } = require("../utils/model")
var { aesEncrypt, keys, checkUsername } = require("../utils");


/* GET users listing. */
//添加房间详情
router.get('/roomadd', function (req, res) {
    checkUsername(req, res, username => {
        res.render('roomadd',{username})
    })
});

//查看所有房间
router.get('/roomlist', function (req, res, next) {
    checkUsername(req, res, username => {
        RoomModel.find({}, {}).then(data => {
            console.log(data)
            res.render("roomlist", { data, username })
            // res.render("roomlist")
        })
    })
});

//编辑房间详情
router.get('/roomupdate', function (req, res) {
    var { _id } = req.query;
    checkUsername(req, res, username => {
        RoomModel.findOne({ _id }).then(result => {
            res.render('roomupdate', { result, username })
        })
    })
});

//提交更新房间详情
router.post("/roomupdate/updateone", (req, res) => {
    var { rnum, food, moeny, phone, state, alt, id } = req.body;
    console.log(food, moeny, phone, state, alt, id)
    checkUsername(req, res, username => {
        RoomModel.updateMany({ rnum }, {
            $set: { food, moeny, phone, state, alt, id }
        }).then(result => {
            RoomModel.find({}, {}).then(data => {
                console.log(data)
                res.render("roomlist", { data, username })
                // res.render("roomlist")
            })
        })
    })
})

//添加房间详情提交数据
router.post('/roomadd/submit', function (req, res) {
    var body = req.body;
    console.log(body)
    RoomModel.findOne({
        rnum: body.rnum,
    }).then(data => {
        if (data) {
            res.send(`<script>alert('房间详情已被添加');location.href='/room/roomlist'</script>`)
        } else {
            RoomModel.insertMany(body)
                .then(result => {
                    res.send(`<script>alert('添加成功');location.href='/room/roomlist' </script>`)
                })
                .catch(err => {
                    res.send(`<script>alert('添加失败');location.href='/room/roomlist' </script>`)

                })
        }
    })
});
router.get('/removeone', function (req, res) {
    var { _id } = req.query;
    RoomModel.remove({
        _id
    }).then(result => {
        res.json({
            code: 200,
            result,
            msg: '删除成功'
        })
    })
})




module.exports = router;